package com.originskyseed.platform.count.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.mongodb.api.MongoUtil;
import com.originskyseed.platform.count.i18n.CountResponseMsg;
import com.originskyseed.platform.count.model.Online;
import com.originskyseed.platform.count.service.IOnlineService;
import com.originskyseed.platform.count.vo.request.OnlineVO;

/**
 * @author tao
 * @date 2020/8/3 16:19
 */
@Controller
@RequestMapping("/count")
@BaseLocaleResource(localeFileName = "i18n_count")
public class OnlineController extends BaseController {

	private static final String TABLENAME = "online_user";

	private static final Logger logger = LoggerFactory.getLogger(OnlineController.class);

	@DubboReference
	private IOnlineService onlineService;

	/**
	 * 统计用户时长信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/online.json")
	public BaseResponseBody online(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result;
		try {
			boolean online = onlineService.online(request);
			if (online) {
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.SUCCESS.getMsg()), true);
			} else {
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.USER_IS_LOGOUT.getMsg()), true);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ERROR.getMsg()), false);
		}
		return result;
	}

	/**
	 * 强制下线
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/offline.json")
	public BaseResponseBody offline(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result;
		try {
			String sessionId = this.getParameterString("sessionId", null);
			boolean offline = onlineService.offline(sessionId);
			if (offline) {
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.SUCCESS.getMsg()), true);
			} else {
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.USER_IS_LOGOUT.getMsg()), true);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ERROR.getMsg()), false);
		}
		return result;
	}

	/**
	 * 用户在线时长列表
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/queryOnlineList.json")
	public BaseResponseBody queryOnlineList(HttpServletRequest request) throws Exception {
		BaseResponseBody result;
		try {
			OnlineVO countVO = this.getParameterBean(OnlineVO.class);
			BasePage<Online> page = new BasePage<>(countVO.getPageNo(), countVO.getPageSize());
			Query query = new Query();
			Criteria criteria = new Criteria();
			if (StringUtils.isNotBlank(countVO.getAccount())) {
				criteria.and("account").is(countVO.getAccount());
			}
			if (StringUtils.isNotBlank(countVO.getUserName())) {
				criteria.and("userName").is(countVO.getUserName());
			}
			if (countVO.getSource() != null) {
				criteria.and("source").is(countVO.getSource());
			}
			if (countVO.getStatus() != null) {
				criteria.and("status").is(countVO.getStatus());
			}
			if (countVO.getStartTime() != null && countVO.getEndTime() != null) {
				criteria.and("createTime").lte(countVO.getEndTime()).gte(countVO.getStartTime());
			} else if (countVO.getStartTime() != null) {
				criteria.and("createTime").gte(countVO.getStartTime());
			} else if (countVO.getEndTime() != null) {
				criteria.and("createTime").lte(countVO.getEndTime());
			}
			query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC, "status"));
			List<JSONObject> resultList = MongoUtil.getInstance().selectListByPage(query, page, JSONObject.class, TABLENAME);
			page.setResults(JSONArray.parseArray(JSONObject.toJSONString(resultList), Online.class));
			Integer totalRecord = Math.toIntExact(MongoUtil.getInstance().selectCountByQuery(query, TABLENAME));
			page.setTotalRecord(totalRecord);
			page.setTotalPage(totalRecord % page.getPageSize() == 0 ? totalRecord / page.getPageSize() : totalRecord / page.getPageSize() + 1);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.SUCCESS.getMsg()), null, page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ERROR.getMsg()), false);
		}
		return result;
	}

}
